package com.item.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.item.entity.WxUser;
import com.item.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhang-rongyao
 * @version V1.0
 * @Package com.item.controller
 * @date 2021/8/9 11:01
 */
@Controller
public class UserLoginController {

    @Autowired
    UserService userService;

    @RequestMapping(value = {"", "/", "/index"}, method = RequestMethod.GET)
    public String index(Model model, HttpServletRequest request) {
        WxUser WxUser = (WxUser) request.getSession().getAttribute("user");
        model.addAttribute("user", WxUser);
        return "users/index";
    }

    @RequestMapping(value = {"/login"}, method = RequestMethod.GET)
    public String loginIndex() {

        return "users/login";
    }

    @RequestMapping(value = {"/login"}, method = RequestMethod.POST)
    public String login(@RequestParam(name = "account") String name, @RequestParam(name = "password") String password,
                        Model model, HttpServletRequest request) {
        QueryWrapper<WxUser> wrapper = new QueryWrapper<>();
        wrapper.eq("account", name);
        WxUser user = userService.getOne(wrapper);
        String pwd = user.getPassword();

        //密码比对
        if (pwd.equals(password)) {
            model.addAttribute("user", user);

            request.getSession().setAttribute("user", user);
            return "redirect:/index";
        } else {
            return "common/error";
        }
    }
}
